package com.cykj.service.impl;

import com.cykj.dto.ResponseDTO;
import com.cykj.entity.UserDO;
import com.cykj.mapper.UserMapper;
import com.cykj.service.IUserService;
import com.cykj.util.BCryptUtil;
import com.cykj.util.JwtUtils;
import com.cykj.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * Project:JDMS
 * Package:com.cykj.service.impl
 *
 * @Description:
 * @Author:其一
 * @CreateTime: 2025-07-24-09-58
 */
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public ResponseDTO login(UserVO userVO) {
        UserDO userDO = userMapper.login(userVO);
        if (userDO == null) {
            return ResponseDTO.error(4, "用户名不存在", null);
        }
        if (!BCryptUtil.matches(userVO.getUserPassword(), userDO.getUserPassword())) {
            return ResponseDTO.error(5, "密码错误", null);
        }

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("userId", userDO.getUserId());
        String token = JwtUtils.generateJwt(hashMap);

        String redisKey = "Token:login:" + token;
        redisTemplate.opsForValue().set(redisKey, hashMap, 5, TimeUnit.MINUTES);

        return ResponseDTO.success("登录成功",token);
    }

    @Override
    public ResponseDTO register(UserVO userVO) {
        userVO.setUserPassword(BCryptUtil.encrypt(userVO.getUserPassword()));
        Integer res = userMapper.register(userVO);
        if (res != null && res != 0) {
            return ResponseDTO.success("注册成功");
        }
        return ResponseDTO.error("注册失败");
    }
}
